let server = require("express")();
let expressStatic = require("express-static")
let mysql = require("mysql")
const port = 81;

let sql = mysql.createConnection({
    host: 'localhost',
    user: 'root',
    password: '123456',
    database: 'student',
    timezone: "08:00"
});

server.get('/select', function(request, response) {
    sql.query(`SELECT * FROM student`, (error, data) => {
        if (error) {
            console.log(error)
            response.send("error")
        } else {
            response.send(JSON.stringify(data))
        }
    })
})
server.get('/shanchu', function(request, response) {
    sql.query(`DELETE FROM student WHERE id=${request.query.id}`, function(error, data) {
        if (error) {
            console.log(error)
            response.send("error")
        } else {
            response.send("success")
        }
    })
})

server.get('/xinzhen', function(request, response) {
    let p = request.query;
    sql.query(`INSERT INTO student (name,age,sex,city,date) VALUES ("${p.name}","${p.age}","${p.sex}","${p.city}","${p.joinDate}")`, (error, data) => {
        if (error) {
            console.log(error)
            response.send("error")
        } else {
            response.send("success")
            console.log(`新增学生${p.name}操作成功`)
        }
    })
})


server.get('/bianji', function(request, response) {
    let p = request.query;
    sql.query(`UPDATE student set name="${p.name}",age="${p.age}",sex="${p.sex}",city="${p.city}",date="${p.Date}" WHERE id="${p.id}"`, (error, data) => {
        if (error) {
            console.log(error)
            response.send("error")
        } else {
            response.send("success")
        }
    })
})





server.get('/add', function(request, response) {
    let p = request.query;
    sql.query(`INSERT INTO user (name,password) VALUES ("${p.name}","${p.password}")`, (error, data) => {
        if (error) {
            console.log(error)
            response.send("error")
        } else {
            response.send("success")
        }
    })
})





server.get('/haha', function(request, response) {
    let p = request.query;
    sql.query(`SELECT *  from user WHERE name="${p.username}"`, (error, data) => {
        if (error) {
            console.log(error)
            response.send("error")
        } else {
            sql.query(`select password from user where name="${p.username}"`, (error, data) => {
                if (error) {
                    response.end("password error")
                } else {
                    response.send(JSON.stringify(data))
                }
            })
        }
    })
})

sql.connect();

server.use(expressStatic(__dirname + '/static'))

server.listen(port);
console.log(`server is running at ${port}`)